<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addDialog">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <!-- 适配table -->
          <template #default="scope">
            {{ formatChargeType(scope.row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="edit(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :title="`${form.id ?'添加计费规则':'编辑计费规则'}`"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="80px" :label-position="labelPosition">
        <el-form-item label="计费规则编号" prop="ruleNumber">
          <el-input v-model="form.ruleNumber" placeholder="请输入计费规则编号" />
        </el-form-item>
        <el-form-item label="计费规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入计费规则名称" />
        </el-form-item>
        <el-form-item label="计费方式（全天收费）" prop="chargeType">
          <el-radio v-model="form.chargeType" label="duration" border>备选项1</el-radio>
          <el-radio v-model="form.chargeType" label="partition" border>备选项2</el-radio>
          <el-radio v-model="form.chargeType" label="turn" border>备选项2</el-radio>
        </el-form-item>
        <div class="box">
          <el-form-item label="免费时长">
            <el-input v-model="form.freeDuration" class="al" placeholder="请输入免费时长" />
            <span>分钟</span>
          </el-form-item>
          <el-form-item label="收费上限">
            <el-input v-model="form.chargeCeiling" class="al" placeholder="请输入收费上限" />
            <span>元</span>
          </el-form-item>
        </div>
        <el-form-item
          v-if="form.chargeType === 'duration'"
          label="计费规则"
          prop="durationTime"
        >
          <br>
          <div class="billingRules">
            <span>每</span>
            <el-form-item prop="durationTime">
              <el-input
                v-model="form.durationTime"
                size="small"
                style="width: 110px"
                placeholder="请输入时长"
              />
            </el-form-item>
            <el-form-item prop="durationType">
              <el-select
                v-model="form.durationType"
                placeholder="请选择"
                size="small"
              >
                <el-option label="小时" value="hour" />
                <el-option label="分钟" value="minute" />
              </el-select>
            </el-form-item>
            <el-form-item prop="durationPrice">
              <el-input
                v-model="form.durationPrice"
                size="small"
                style="width: 110px"
                placeholder="请输入"
              />
            </el-form-item>
            <span>元</span>
          </div>
        </el-form-item>

        <el-form-item
          v-else-if="form.chargeType === 'turn'"
          label="计费规则"
          prop="turnPrice"
        >
          <div class="billingRules">
            <span>每次</span>
            <el-form-item prop="turnPrice">
              <el-input
                v-model="form.turnPrice"
                size="small"
                style="width: 120px"
                placeholder="请输入"
              />
            </el-form-item>
            <span>元</span>
          </div>
        </el-form-item>

        <el-form-item v-else label="计费规则" prop="partitionFrameTime">
          <br>
          <div class="guizhe">
            <div class="billingRules">
              <el-form-item prop="partitionFrameTime">
                <el-input
                  v-model="form.partitionFrameTime"
                  size="small"
                  style="width: 90px"
                  placeholder="请输入"
                />
              </el-form-item>
              <span>小时内，每小时收费</span>
              <el-form-item prop="partitionFramePrice">
                <el-input
                  v-model="form.partitionFramePrice"
                  size="small"
                  style="width: 90px"
                  placeholder="请输入"
                />
              </el-form-item>
              <span>元</span>
            </div>
            <div class="billingRules">
              <span>每增加</span>
              <el-form-item prop="partitionIncreaseTime">
                <el-input
                  v-model="form.partitionIncreaseTime"
                  size="small"
                  style="width: 90px"
                  placeholder="请输入"
                />
                <span>小时，增加</span>
              </el-form-item>
              <el-form-item prop="partitionIncreasePrice">
                <el-input
                  v-model="form.partitionIncreasePrice"
                  size="small"
                  style="width: 90px"
                  placeholder="请输入"
                />
              </el-form-item>
              <span>元</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRuleListAPI, addcarRuleAPI, editRuleAPI, getcarRuleAPI } from '@/api/car'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      labelPosition: 'top',
      form: {
        'ruleNumber': '',
        'ruleName': '',
        'freeDuration': '',
        'chargeCeiling': '',
        'chargeType': 'duration',
        'durationTime': '',
        'durationPrice': '',
        'durationType': '',
        'turnPrice': null,
        'partitionFrameTime': null,
        'partitionFramePrice': null,
        'partitionIncreaseTime': null,
        'partitionIncreasePrice': null
      },
      rules: {
        ruleNumber: [{
          required: true,
          message: '请输入计费规则编号',
          trigger: ['blur', 'change']
        }],
        ruleName: [{
          required: true,
          message: '请输入计费规则编号',
          trigger: ['blur', 'change']
        }],
        chargeType: [{
          required: true,
          message: '请选择计费方式',
          trigger: ['blur', 'change']
        }],
        durationTime: [
          { required: true, message: '请输入计费规则', trigger: 'change' }
        ],
        turnPrice: [
          { required: true, message: '请输入计费规则', trigger: 'change' }
        ],
        partitionFrameTime: [
          { required: true, message: '请输入计费规则', trigger: 'change' }
        ]

      },
      ruleList: [],
      params: {
        page: 1,
        pageSize: 10
      },
      total: 0,
      // 弹窗状态默认关闭
      rentDialogVisible: false,
      // 适配收费状态
      formatChargeType(type) {
        const TYPEMAP = {
          'duration': '按时长收费',
          'turn': '按次收费',
          'partition': '分段收费'
        }
        return TYPEMAP[type]
      }
    }
  },
  // 渲染列表 遍历 钩子函数
  mounted() {
    this.getRuleList()
  },
  methods: {
    closeDialog() {
      this.rentDialogVisible = false
    },
    // 获取规则列表
    async getRuleList() {
      const res = await getRuleListAPI(this.params)
      this.ruleList = res.data.rows
    },

    // 导出excel
    // 导出excel
    async exportToExcel() {
      const res = await getRuleListAPI(this.params)
      const tableHeader = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      // 以excel表格的顺序调整后端数据
      const sheetData = res.data.rows.map((item) => {
        const _obj = {}
        tableHeader.forEach(key => {
          // 赋值
          // 针对计费规则做处理
          if (key === 'chargeType') {
            _obj[key] = this.formatChargeType(item[key])
          } else {
            _obj[key] = item[key]
          }
        })
        return _obj
      })
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },

    // 点击新增弹窗
    addDialog() {
      this.rentDialogVisible = true
    },
    // 点击确定  新增弹窗  兜底校验 适配新增和编辑模式
    confirm() {
      // 兜底校验
      this.$refs.form.validate(async(val) => {
        if (!val) return
        // 如果有id 调用编辑接口
        if (this.form.id) {
          await editRuleAPI(this.form)
          this.$message.success('编辑停车计费规则成功')
        } else {
          // 没有id 调用新增接口
          await addcarRuleAPI(this.form)
          this.$message.success('添加计费规则成功')
        }
        this.getRuleList() // 点击确定并输入或修改完内容后 不管是新增还是编辑都得重新渲染列表
        this.$refs.form.resetFields() // 重置表单
        // 免费时长 和收费上限这两个没有绑定prop 所以手动清空
        this.form.freeDuration = ''
        this.form.chargeCeiling = ''
        this.rentDialogVisible = false // 关闭弹窗
      })
    },
    // 点击编辑===》回显
    async edit(id) {
      this.rentDialogVisible = true // 点击编辑 弹窗为开启状态
      const res = await getcarRuleAPI(id) // 让接口里返回来的值赋值给res
      console.log(res)
      this.form = res.data // 表单拿到res里的data
    }
  }}

</script>

<style lang="scss" scoped>
.guizhe {
  margin-top: -52px;
}
.billingRules {
  width: 350px;
  display: flex;
  justify-content: space-between;
}

.al {
  width: 180px;
}
.box {
  display: flex;

}
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
